package com.ai.wxy.spring.storm.test.drpc;

import lombok.extern.slf4j.Slf4j;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.List;
import java.util.Map;

/**
 * 获取粉丝人员
 *
 * @author 石头
 * @Date 2019/12/18
 * @Version 1.0
 **/
@Slf4j
public class GetFollowersBolt extends BaseRichBolt{
    private OutputCollector collector;
    @Override
    public void prepare(Map<String, Object> stormConf, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
    }

    @Override
    public void execute(Tuple input) {
        try {
            Long requestId = input.getLong(0);
            String tweeter = input.getString(1);
            List<String> followers = TiwtterReachTopology.FOLLOWERS_DB.get(tweeter);
            if (followers==null || followers.isEmpty()){
                return;
            }
            for (String follower : followers) {
                collector.emit(input, new Values(requestId, follower));
            }
        }finally {
            // 如果使用BaseRichBolt 必须手动提交Ack / Fail
            // 如果BaseBasicBolt，ack 自动调用的，这里必须注意，否则导致 Bolt 如果return 时，
            // 下一个Blot无法获取数据 ，同时 finishBatch 无法知道处理完毕
            collector.ack(input);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("Id", "Follower"));
    }
}
